<template>
  <view class="center">
    <div class="topCard">
      <div class="Title">
        <div class="backIcon" @click="backHome">
          <IconFont name="rect-left" color="#342e2c" size="18"></IconFont>
        </div>
        <div class="TitleText">地图选址</div>
        <div class="titleRight"></div>
      </div>
    </div>
    <div class="mapCard">
      <div id="mapContainer" class="mapContainer" v-if="showMap"></div>
    </div>
    <div class="floatCardAddressList">
      <div class="nowAddress">当前位置:{{ mapAddress }}</div>
      <div class="selectAddressList">
        <div
          v-for="item in selectAddressList"
          :key="item.id"
          class="listCard"
          @click="selectAddressToBan(item)"
        >
          <div class="left">
            <IconFont name="location2" color="#6b6b83" size="20"></IconFont>
          </div>
          <div class="right">
            <div class="leftText">
              <div class="topTitle">{{ item.name }}</div>
              <div class="bottomAddress">
                {{ item.district }}{{ item.address }}
              </div>
            </div>

            <div class="rightBtn" @click="selectThisAddress($event, item)">
              确定
            </div>
          </div>
        </div>
      </div>
    </div>
  </view>
</template>
<script lang="js" setup name="MapDialog">
import {
  ComponentInternalInstance,
  getCurrentInstance,
  onMounted,
  ref,
  shallowRef,
  toRaw,
  defineEmits,
  nextTick
} from "vue";
import Taro, { eventCenter, useDidShow, useDidHide } from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro';

import AMapLoader from "@amap/amap-jsapi-loader";
const showMap=ref(false)
const MAP_KEY = "39cae8cb35cd12d8c605f324788e3040";
const MAP_CODE = "af5a7657629f4653a0e39888ed6c75e1";
const emits = defineEmits('mapSelectAddress');
const mapAddress = ref('当前位置')
const selectAddressList = ref([{
  name: '测试1',
  address: '测试',
  location: '116.39748,39.90923'
},
{
  name: '测试22',
  address: '测试2',
  location: '116.39748,39.90923'
},
{
  name: '测试23',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试24',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试25',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试26',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试27',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试28',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试29',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试212',
  address: '测试2',
  location: '116.39748,39.90923'
}, {
  name: '测试211',
  address: '测试2',
  location: '116.39748,39.90923'
},
])

// 地图实例对象
const AMapInstance = shallowRef(null);
const marker = shallowRef();
/**
 * 初始化地图
 * @return {Promise<void>}
 */
async function initMap() {
  showMap.value=true
  try {
    if (AMapInstance.value !== null) {
      AMapInstance.value.clearMap();
    }
    await AMapLoader.load({
      key: MAP_KEY,
      // 安全密钥
      securityJsCode: MAP_CODE,
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.Autocomplete",
        "AMap.Geolocation",//定位
        "AMap.Geocoder",// 地址解析
        "AMap.Driving",//驾车规划
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
    AMapInstance.value = new AMap.Map("mapContainer", {
      //设置地图容器id
      viewMode: "3D", //是否为3D地图模式
      zoom: 16, //初始化地图级别
      center: [87.630238, 43.859831], //初始化地图中心点位置
    });
    //绑定地图移动与缩放事件
    AMapInstance.value.on('dragging', logMapInfo);
    // 自己本身定位
    addMyAddressMarker()
  } catch (err) {
    console.warn(err);
  }


}
/**
 * 地图逆地理编码插件
 * @param LngLat
 */
function getAddress(LngLat) {
  const geoCoder = new AMap.Geocoder({
    city: '乌鲁木齐'
  });
  return new Promise((resolve, reject) => {
    geoCoder.getAddress(LngLat, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        resolve(result);
      } else {
        reject(result);
      }
    });
  });
}
/**
 * 添加我的地址标记
 */
function addMyAddressMarker() {
  marker.value = new AMap.Marker(); // 创建标记对象
  marker.value.setPosition([87.630238, 43.859831]); // 设置标记位置
  AMapInstance.value.add(marker.value); // 将标记添加到地图实例中
  getAddress([87.630238, 43.859831]).then((res) => {
    mapAddress.value = replaceField(res.regeocode)
    floatInfoWindow()
  })
}

function replaceField(data) {
  console.log(data)
  // 通过方法去除存在字段
  var noProvince = data.formattedAddress.replace(new RegExp(data.addressComponent.province, "g"), "");
  var noCity = noProvince.replace(new RegExp(data.addressComponent.city, "g"), "");
  var noDistrict = noCity.replace(new RegExp(data.addressComponent.district, "g"), "");
  var address = noDistrict.replace(new RegExp(data.addressComponent.township, "g"), "");
  console.log(address)
  return address
}
//显示地图层级与中心点信息
function logMapInfo() {
  let zoom = AMapInstance.value.getZoom(); //获取当前地图级别
  let center = AMapInstance.value.getCenter(); //获取当前地图显示中心位置
  getAddress([center.lng, center.lat]).then((res) => {
    mapAddress.value = replaceField(res.regeocode)
    floatInfoWindow(zoom)
  })
  // 添加一个浮标

};
function floatInfoWindow(zoom) {
  var content = [
    `<div style='display:flex;flex-flow:column;align-items:center;width:150px;height:120px;'>
    <div class='infoPao' style='min-width: 100px; min-height: 20px;border: 1px solid #000; background-color: #fff;text-align: center;padding: 2px;font-size:14px;border-radius: 10px;'>${mapAddress.value}</div>
    <div style='width:2px;height:30px;background-color:#000;'>
      </div>
      <div style='width:10px;height:10px;background-color:#ffb114;border-radius:50%;margin:0 auto;'><div>
      </div>
  `,
  ];
  var infoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: content.join("<br>"),
    offset: new AMap.Pixel(0, 0),
  });

  infoWindow.open(AMapInstance.value, AMapInstance.value.getCenter());
}
function selectAddressToBan(item) {
  console.log(item)
}
function selectThisAddress(e,item) {
  console.log(e,item)
  e.stopPropagation(); // 阻止冒泡
  if (Taro.getCurrentInstance().preloadData?.addressList && Taro.getCurrentInstance().preloadData?.selectInput) {
    // 做一些处理存在我想要的值
    Taro.getCurrentInstance().preloadData.addressList[Taro.getCurrentInstance().preloadData.selectInput].address=item.name
    Taro.getCurrentInstance().preloadData.addressList[Taro.getCurrentInstance().preloadData.selectInput].location=item.location
    console.log(Taro.getCurrentInstance().preloadData)
  }
  Taro.navigateBack({
    delta: 1//表示回到上一页面
  })
}

function toInitMap() {
  nextTick(() => {

    initMap();
  })
}

function backHome() {
  Taro.navigateTo({
    url: '/pages/addressSelect/index'
  })
}
function DidMap() {
  if (AMapInstance.value) {
    AMapInstance.value.destroy();
    AMapInstance.value = null;
  }
}
useDidHide(() => {
  DidMap()
  showMap.value=false
})
onMounted(() => {
  nextTick(() => {
    initMap();
  })
})
defineExpose({ toInitMap, DidMap });
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
